package com.fhnew.app.ui.activity.recomend.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResTeam;
import com.fhnew.app.model.network.entity.req.ResTeamlist;

import com.fhnew.app.util.DoubleDatePickerDialog;
import com.fhnew.app.widget.MyRecyclerView;
import com.fhnew.app.util.OnEndLessScrollListener;
import com.fhnew.app.util.OnItemClickListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/9/25.
 */

public class TeamtableFragment extends Fragment {

    private EditText teamid;
    private TextView teamstarttime;
    private TextView teamendtime;
    private TextView teamsearch;
    private TextView teamclear;
    private MyRecyclerView teamlist;
    private TextView teamchongzhi;
    private TextView teamtiqu;
    private TextView teamtouzhu;
    private TextView teamfanyong;
    private EditText leaderteamid;
    //    ArrayList<String> list = new ArrayList<>();
    private ArrayList<ResTeam.DataBean> dataBeans = new ArrayList<>();
    private Adapter adapter;
    private String starttime;
    private String endtime;
    private View mHeaderView;

    private TextView teamuser;
    private TextView zongaddmoney;
    private TextView zongdama;
    private TextView teamchengyuan;
    private TextView teamgetmoney;
    private TextView teamefanyong;

    private String userAccount;
    private String leaderid;

    private int page;//初始页数

    private OnEndLessScrollListener onEndLessScrollListener;

    private void initView (View view) {
        teamid = view.findViewById(R.id.teamid);
        teamstarttime = view.findViewById(R.id.teamstarttime);
        teamendtime = view.findViewById(R.id.teamendtime);
        teamsearch = view.findViewById(R.id.teamsearch);
        teamclear = view.findViewById(R.id.teamclear);
        teamlist = view.findViewById(R.id.teamlist);
        teamchongzhi = view.findViewById(R.id.teamchongzhi);
        teamtiqu = view.findViewById(R.id.teamtiqu);
        teamtouzhu = view.findViewById(R.id.teamtouzhu);
        teamfanyong = view.findViewById(R.id.teamfanyong);
        leaderteamid = view.findViewById(R.id.leaderteamid);


        teamstarttime.setOnClickListener(onClickListener);
        teamendtime.setOnClickListener(onClickListener);
        teamsearch.setOnClickListener(onClickListener);
        teamclear.setOnClickListener(onClickListener);
    }

    @Nullable
    @Override
    public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.teamtablelayout, null);
        initView(container);
        return container;
    }

    @Override
    public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化控件
        teamlist.setNestedScrollingEnabled(false);
        page = 0;


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        onEndLessScrollListener = new OnEndLessScrollListener(linearLayoutManager) {
            @Override
            public void getMoreData (int currentPage) {
                //下拉加载的时候页数加1
                searchcommission(++page);
            }
        };
        teamlist.setLayoutManager(linearLayoutManager);
        mHeaderView = View.inflate(getContext(), R.layout.teamtableheader, null);
        //初始化头部布局
        InitHeaderView();
        teamlist.addHeaderView(mHeaderView);

        adapter = new Adapter();
        teamlist.setAdapter(adapter);
        teamlist.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

//添加滑动监听
        teamlist.addOnScrollListener(onEndLessScrollListener);
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd");// a为am/pm的标记
        Date date = new Date();// 获取当前时间
//        System.out.println("现在时间：" + sdf.format(date)); // 输出已经格式化的现在时间（24小时制）
//        SYSOUtils.sOut_("当前时间是+++++++++++++++++++++++++" + sdf.format(date));
        starttime = sdf.format(date);
        endtime = sdf.format(date);
    }

    @Override
    public void onHiddenChanged (boolean hidden) {
        super.onHiddenChanged(hidden);
        page = 0;
        searchcommission(page);
    }

    private void InitHeaderView () {
        teamuser = (TextView) mHeaderView.findViewById(R.id.teamuser);
        zongaddmoney = (TextView) mHeaderView.findViewById(R.id.zongaddmoney);
        zongdama = (TextView) mHeaderView.findViewById(R.id.zongdama);
        teamchengyuan = (TextView) mHeaderView.findViewById(R.id.teamchengyuan);
        teamgetmoney = (TextView) mHeaderView.findViewById(R.id.teamgetmoney);
        teamefanyong = (TextView) mHeaderView.findViewById(R.id.teamefanyong);
    }

    private void searchcommission (int page) {
        HttpJsonUtils.getHttpApiInstance()
                .getteam(Constants.getuseAdress() + "api/m/promotion/team", page + "", "10", starttime, endtime, userAccount, leaderid, UserModel.Token).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResTeam>(TeamtableFragment.this) {
                .subscribe(new CustomObserver<ResTeam>() {
                    @Override
                    protected void onCustomNext (ResTeam resCommission) {
                        if (resCommission.code == 0 && resCommission.data.size() > 0) {
                            dataBeans.clear();
                            dataBeans.addAll(resCommission.data);
                            adapter.notifyDataSetChanged();
//                            teamuser.setText("直属成员:" + resCommission.otherData.userDirectly);
                            zongaddmoney.setText("总充值:" + resCommission.otherData.totalRecharge);
                            zongdama.setText("总打码:" + resCommission.otherData.totalBet);
//                            teamchengyuan.setText("团队成员:" + resCommission.otherData.userTeam);
                            teamgetmoney.setText("总提现:" + resCommission.otherData.totalDrawing);
                            teamefanyong.setText("总返佣:" + resCommission.otherData.totalMoney);
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });

    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            switch (view.getId()) {
                case R.id.teamstarttime:
                    Calendar c = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            teamstarttime.setText("开始时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            starttime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), false).show();
                    break;
                case R.id.teamendtime:
                    Calendar c2 = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            teamendtime.setText("结束时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            endtime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DATE), false).show();
                    break;
                case R.id.teamsearch:
                    if (TextUtils.isEmpty(teamid.getText().toString()) && TextUtils.isEmpty(leaderteamid.getText().toString())) {
                        userAccount = teamid.getText().toString();
                        leaderid = leaderteamid.getText().toString();
                    } else {
                        userAccount = "";
                        leaderid = "";
                    }
                    searchcommission(page);
                    break;
                case R.id.teamclear:
                    starttime = "";
                    endtime = "";
                    teamstarttime.setText("开始时间");
                    teamendtime.setText("结束时间");
                    break;
            }
        }
    };




    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter.MViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter.MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.teamitem, viewGroup, false));
        }


        @Override
        public void onBindViewHolder (@NonNull MViewHolder holder, int postion) {
            if (postion % 2 != 0) {
                holder.teamitem.setBackgroundResource(R.color.blue);
            } else {
                holder.teamitem.setBackgroundResource(R.color.royalblue);
            }
            holder.userid.setText("" + dataBeans.get(postion).user_account);
            holder.useradd.setText("" + dataBeans.get(postion).reMoney);
            holder.userget.setText("" + dataBeans.get(postion).drMoney);
            holder.usertouzhu.setText("" + dataBeans.get(postion).betMoney);
            holder.userfanyong.setText("" + dataBeans.get(postion).money);
        }


        @Override
        public int getItemCount () {
            return dataBeans.size();
        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            LinearLayout teamitem;
            TextView userid, useradd, userget, usertouzhu, userfanyong;

            MViewHolder (View itemView) {
                super(itemView);
                teamitem = (LinearLayout) itemView.findViewById(R.id.teamitem);
                userid = (TextView) itemView.findViewById(R.id.userid);
                useradd = (TextView) itemView.findViewById(R.id.useradd);
                userget = (TextView) itemView.findViewById(R.id.userget);
                usertouzhu = (TextView) itemView.findViewById(R.id.usertouzhu);
                userfanyong = (TextView) itemView.findViewById(R.id.userfanyong);
            }
        }
    }
}
